package com.tudouji.project.produce.service.impl;

import com.flow.service.pojo.BasePojo;
import com.flow.service.pojo.ResultParam;
import com.flow.service.pojo.flow.FlowTempNode;
import com.flow.service.pojo.result.FlowResult;
import com.flow.service.process.service.IFlowBaseService;
import com.flow.service.process.service.impl.FlowTempNodeServiceImpl;
import com.github.pagehelper.PageHelper;
import com.tudouji.common.utils.IdUtils;
import com.tudouji.common.utils.SecurityUtils;
import com.tudouji.common.utils.StringUtils;
import com.tudouji.common.utils.sql.SqlUtil;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.framework.web.page.PageDomain;
import com.tudouji.framework.web.page.TableSupport;
import com.tudouji.project.flow.utils.FlowProcessUtil;
import com.tudouji.project.harvest.domain.Qaform;
import com.tudouji.project.harvest.service.IQaformService;
import com.tudouji.project.organization.domain.Organization;
import com.tudouji.project.organization.service.IOrganizationService;
import com.tudouji.project.permission.domain.Salespermission;
import com.tudouji.project.permission.service.impl.SalespermissionServiceImpl;
import com.tudouji.project.produce.domain.Pickinglist;
import com.tudouji.project.produce.domain.Pickinglistitem;
import com.tudouji.project.produce.domain.Whinapply;
import com.tudouji.project.produce.domain.Whinapplyitem;
import com.tudouji.project.produce.mapper.WhinapplyMapper;
import com.tudouji.project.produce.service.*;
import com.tudouji.project.product.domain.Products;
import com.tudouji.project.product.domain.Salesspecification;
import com.tudouji.project.product.service.IProductsService;
import com.tudouji.project.product.service.ISalesspecificationService;
import com.tudouji.project.store.mapper.StoreroomMapper;
import com.tudouji.project.system.domain.SysDept;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.service.impl.BusinesscodeServiceImpl;
import com.tudouji.project.system.service.impl.SysDeptServiceImpl;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * 入库申请单Service业务层处理
 *
 * @author tudouji
 * @date 2022-06-01
 */
@Service
public class WhinapplyServiceImpl implements IWhinapplyService, IFlowBaseService {
    @Autowired
    private WhinapplyMapper whinapplyMapper;

    @Autowired
    private IPickinglistService pickinglistService;

    @Autowired
    private IPickinglistitemService pickitemService;
    @Autowired
    private IProductsService productsService;

    @Autowired
    private ISalesspecificationService specificationService;

    @Autowired
    private IProduceplanService produceplanService;

    @Autowired
    private IOrganizationService orgService;

    @Autowired
    private BusinesscodeServiceImpl codeService;

    @Autowired
    private FlowTempNodeServiceImpl nodeService;

    @Autowired
    private FlowProcessUtil processUtils;

    @Autowired
    private IWhinapplyitemService itemService;

    @Autowired
    private SalespermissionServiceImpl permissionService;

    @Autowired
    private IQaformService qaformService;

    @Autowired
    private StoreroomMapper storeroomMapper;

    @Autowired
    private SysDeptServiceImpl sysDeptService;
    /**
     * 查询入库申请单
     *
     * @return 入库申请单
     */
    @Override
    public Whinapply selectWhinapplyById(Long id) {
        Whinapply whinapply = whinapplyMapper.selectDetailById(id);
//        Qaform qa = qaformService.selectQaformByLinkId(whinapply.getGuid());
//        whinapply.setQaform(qa);
        return whinapply;
    }

    /**
     * 查询入库申请单列表
     *
     * @param whinapply 入库申请单
     * @return 入库申请单
     */
    @Override
    public List<Whinapply> selectWhinapplyList(Whinapply whinapply) {
        return whinapplyMapper.selectWhinapplyList(whinapply);
    }

    @Override
    public List<Whinapply> selectWhinapplyList(Whinapply apply, String status, String functionType) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (apply == null) {
            apply = new Whinapply();
        }
        apply.setFlowid("33");
        apply.setCreateBy(user.getUserId());
        if (org.apache.commons.lang.StringUtils.isNotBlank(status)) {
            // 待处理
            if (status.equals("00")) {
                startPage();
                return whinapplyMapper.selectApplyPendingList(apply);
            } else {
                String[] sts = status.split(",");
                Integer[] stss = (Integer[]) ConvertUtils.convert(sts, Integer.class);
                apply.setStats(stss);
            }
        }
        // 查询用户是否有全局权限
        List<Salespermission> permissions = permissionService.getPermByScAndFuncSYS(user.getUserId(),functionType,"4");
        if (permissions.size()<1) {
            //查询单一库房权限
            List<Salespermission> pers=permissionService.getPermByScAndFuncSYS(user.getUserId(), functionType,"7");
            if(pers.size()>0){
                String[] roomids=new String[pers.size()];
                for(int i=0;i<pers.size();i++){
                    roomids[i]=pers.get(i).getSrguid();
                }
                apply.setRoomids(roomids);
                startPage();
                return whinapplyMapper.selectWhinapplyListBySR(apply);
            }
            //查询库房+部门权限(领料)
            List<Salespermission> pers2=permissionService.getPermByScAndFuncSYS(user.getUserId(), functionType,"3");
            if(pers2.size()>0){
                String[] androomids=new String[pers2.size()];
                String[] anddepids=new String[pers2.size()];
                for(int i=0;i<pers2.size();i++){
                    androomids[i]=pers2.get(i).getSrguid();
                    anddepids[i]=pers2.get(i).getDepartid();
                }
                startPage();
                apply.setAndroomids(androomids);
                apply.setAnddepids(anddepids);
                return whinapplyMapper.selectWhinapplyListByBZ(apply);
            }
            //查询个人
            startPage();
            return whinapplyMapper.selectWhinapplyListByUser(apply);
        }else{
            //全局
            startPage();
            return whinapplyMapper.selectList(apply);
        }
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (com.tudouji.common.utils.StringUtils.isNotNull(pageNum) && com.tudouji.common.utils.StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 新增入库申请单
     *
     * @param whinapply 入库申请单
     * @return 结果
     */
    @Override
    public int insertWhinapply(Whinapply whinapply) {
        return whinapplyMapper.insertWhinapply(whinapply);
    }

    /**
     * 修改入库申请单
     *
     * @param whinapply 入库申请单
     * @return 结果
     */
    @Override
    public int updateWhinapply(Whinapply whinapply) {
        return whinapplyMapper.updateWhinapply(whinapply);
    }

    /**
     * 批量删除入库申请单
     *
     * @param guids 需要删除的入库申请单ID
     * @return 结果
     */
    @Override
    public int deleteWhinapplyByIds(String[] guids) {
        return whinapplyMapper.deleteWhinapplyByIds(guids);
    }

    /**
     * 删除入库申请单信息
     *
     * @param guid 入库申请单ID
     * @return 结果
     */
    @Override
    public int deleteWhinapplyById(String guid) {
        return whinapplyMapper.deleteWhinapplyById(guid);
    }

    @Override
    public AjaxResult getWhinapplyInfo(Long pickinglistid, String productflag) {
        AjaxResult result = new AjaxResult();
        // 查询领料单
        Pickinglist picking = pickinglistService.selectPickinglistByNewId(pickinglistid);

        if (picking.getFlag() == 1) {
            // 领料单明细
            Pickinglistitem item = new Pickinglistitem();
            item.setPickinglistid(picking.getGuid());
            List<Pickinglistitem> itemss = pickitemService.selectPickinglistitemList(item);
            result.put("items", itemss);

            // 查询领料单明细中的产品信息
            Pickinglistitem product = new Pickinglistitem();
            product.setPickinglistid(picking.getGuid());
            //查询非辅料的出库产品
            product.setSearchflag("5");
            List<Products> products = pickitemService.getProducts(product);
            //判断领料明细中的产品是否包含生产成品，如果包含生产成品 则 查询所有的 产品 返回前台，否则只查询生产成品及 领料产品
            int flag = 1;
            if (products.size() > 0) {
                flag = 2;
            }
            // 获取产品 //领料是标准产品时候查询出所在工厂可生产范围的所有产品
            if (flag == 2) {
                Products pro = new Products();
                pro.setStrguid(picking.getStrmid());
                pro.setProflags(productflag.split(","));
                products = productsService.findProducePro(pro);
            } else {
                if (!productflag.equals("3")) {
                    Products pro = new Products();
                    pro.setStrguid(picking.getStrmid());
                    pro.setPickingid(picking.getGuid());
                    pro.setProflags(productflag.split(","));
                    products = productsService.findAllProducePro(pro);
                } else {
                    Products pro = new Products();
                    pro.setPickingid(picking.getGuid());
                    products = productsService.findCpProducePro(pro);
                }
            }
            result.put("products", products);
        } else {
            Products pro = new Products();
            pro.setStrguid(picking.getStrmid());
            pro.setProflags(productflag.split(","));
            result.put("products", productsService.findProducePro(pro));
        }
        result.put("code", 200);
        return result;
    }

    @Override
    public AjaxResult getSpeByproduct(String productid, String type, String types, String stat) {
        // 查询规格
        Salesspecification spe = new Salesspecification();
        spe.setProductguid(productid);
        if (StringUtils.isNotBlank(type)) {
            spe.setType(Integer.parseInt(type));
        }
        if(StringUtils.isNotBlank(stat)){
            String[] strs=stat.split(",");
            Integer[] stats= new Integer[strs.length];
            for(int i=0;i<strs.length;i++){
                stats[i] = Integer.parseInt(strs[i]);
            }
            spe.setStats(stats);
        }
        if(StringUtils.isNotBlank(types)){
            String[] tps=types.split(",");
            Integer[] ps=(Integer[]) ConvertUtils.convert(tps,Integer.class);
            spe.setTypes(ps);
        }
        List<Salesspecification> specifications = specificationService.selectSalesspecificationList(spe);
        return AjaxResult.success(specifications);
    }

    @Override
    @Transactional
    public AjaxResult save(Whinapply apply,Long taskId,String fileIds) {
        SysUser user= SecurityUtils.getLoginUser().getUser();
        //获取领料单信息
        Pickinglist picking=pickinglistService.selectPickinglistById(apply.getPickinglistid());

//        //查询生产计划
//        Produceplan plan= produceplanService.selectProduceplanById(picking.getProduceplanid());
        //查询组织
        Organization org=orgService.selectOrganizationById(picking.getOrgid());

        //入库单数据准备
        apply.setCode(codeService.getCode("3"));
        apply.setProduceplanid(picking.getProduceplanid());
        apply.setPickinglistid(apply.getPickinglistid());
        apply.setSrguid(picking.getStrmid());
        apply.setFlowid("33");
        apply.setStatus(9999);
        apply.setOrgguid(picking.getOrgid());
        apply.setOrgname(org.getName());
        apply.setDepartid(picking.getDepartmentid());
        SysDept dept=sysDeptService.selectDeptById(apply.getDeptId());

        apply.setOperatorid(user.getGuid());
        apply.setCreateBy(user.getUserId());
        apply.setCreateName(user.getNickName());
        String guid=IdUtils.fastSimpleUUID();
        apply.setGuid(guid);

        whinapplyMapper.insertWhinapply(apply);

        apply.setPlatformId(apply.getStrmId());

        for(Whinapplyitem item:apply.getItems()){
            item.setGuid(IdUtils.fastSimpleUUID());
            item.setWhinapplyid(guid);
            itemService.insertWhinapplyitem(item);
        }


        // 获取起始节点
        FlowTempNode node = new FlowTempNode();
        node.setNodeType(1);
        node.setFlowtempId(Long.valueOf(apply.getFlowid()));
        node = nodeService.selectFlowTempNodeList(node).get(0);

        FlowResult result = processUtils.defaultStart(node.getId(), apply, fileIds, user);
        Whinapply app=new Whinapply();
        app.setGuid(guid);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            app.setStatus(result.getNextStat());
            whinapplyMapper.updateWhinapply(app);
        }else{
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.success(result.getMsg());
        }

        picking.setPlatformId(apply.getStrmId());

//        FlowResult result2 = processUtils.defaultApproval(taskId, fileIds, null, picking
//                , user);
//        if (result2.getMsg().equals(ResultParam.SUCCESS)) {
//            Pickinglist pick=new Pickinglist();
//            pick.setGuid(apply.getPickinglistid());
//            pick.setStatus(result2.getNextStat());
//            pickinglistService.updatePickinglist(pick);
//        }else{
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return AjaxResult.success(result2.getMsg());
//        }
        return AjaxResult.success();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult approval(Long id, String fileIds, String opinion, Long taskid) {
        Whinapply apply = whinapplyMapper.selectWhinapplyByAutoId(id);

        apply.setPlatformId(apply.getStrmId());

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        FlowResult result = processUtils.defaultApproval(taskid, fileIds, opinion, apply
                , sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Whinapply pb = new Whinapply();
            pb.setStatus(result.getNextStat());
            pb.setGuid(apply.getGuid());
            this.updateWhinapply(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult refuse(Long id, String fileIds, String opinion, Long taskid, Long refuseNodeid, Long backUserid) {
        Whinapply apply = whinapplyMapper.selectWhinapplyByAutoId(id);

        apply.setPlatformId(apply.getStrmId());

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        FlowResult result = processUtils.defaultRefuse(taskid, fileIds, opinion, apply
                , sysUser, refuseNodeid, backUserid);

        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Whinapply pb = new Whinapply();
            pb.setStatus(result.getNextStat());
            pb.setGuid(apply.getGuid());
            this.updateWhinapply(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult delQaform(Long id, String fileIds, String opinion, Long taskid) {
        Whinapply apply = whinapplyMapper.selectWhinapplyByAutoId(id);
        //修改验收单状态为已删除
        Qaform qa = new Qaform();
        qa.setFoguid(apply.getGuid());
        qa.setStatus(3);
        qaformService.updateQaformByFoGuid(qa);
        return approval(id,fileIds,opinion,taskid);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult del(Long id) {
        Whinapply apply = whinapplyMapper.selectWhinapplyByAutoId(id);
        if(apply.getStatus()!=100){
            SysUser user = SecurityUtils.getLoginUser().getUser();
            apply.setStatus(0);
            whinapplyMapper.updateWhinapply(apply);
            //更新待处理任务
            processUtils.updateTaskByOrderId(id, user, Long.parseLong(apply.getFlowid()));
            return AjaxResult.success();
        }else{
            return AjaxResult.error("不允许删除");
        }

    }

    @Override
    public Whinapply selectWhinapplyByAutoId(Long id) {
        return whinapplyMapper.selectWhinapplyByAutoId(id);
    }

    @Override
    public List<Whinapply> selectList(Whinapply wa) {
        return whinapplyMapper.selectList(wa);
    }


    @Override
    public BasePojo getBaseById(Long id) {
        return selectWhinapplyByAutoId(id);
    }

    @Override
    public BasePojo getBaseByCode(String code) {
        return null;
    }
}
